package com.blrs.service.contract.impl;

import java.sql.Timestamp;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

import com.blrs.common.utils.SecurityUtils;
import com.blrs.common.utils.StringUtils;
import com.blrs.domain.ContractManagementInfo;
import com.blrs.domain.ContractPaymentMethod;
import com.blrs.domain.vo.BusinessMainClassVo;
import com.blrs.domain.vo.ContractPaymentMethodVo;
import com.blrs.mapper.ContractManagementInfoMapper;
import com.blrs.mapper.ContractPaymentMethodMapper;
import com.blrs.service.contract.IContractManagementInfoService;
import com.blrs.system.service.ISysDeptService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;


/**
 * 【请填写功能名称】Service业务层处理
 * 
 * @author ruoyi
 * @date 2023-11-30
 */
@Service
public class ContractManagementInfoServiceImpl implements IContractManagementInfoService
{
    @Autowired
    private ContractManagementInfoMapper contractManagementInfoMapper;
    @Autowired
    private ContractPaymentMethodMapper contractPaymentMethodMapper;
    /**
     * 查询【请填写功能名称】
     * 
     * @param contractId 【请填写功能名称】主键
     * @return 【请填写功能名称】
     */
    @Override
    public ContractManagementInfo selectContractManagementInfoByContractId(String contractId)
    {
        return contractManagementInfoMapper.selectContractManagementInfoByContractId(contractId);
    }

    /**
     * 查询【请填写功能名称】列表
     * 
     * @param contractManagementInfo 【请填写功能名称】
     * @return 【请填写功能名称】
     */
    @Override
    public List<ContractManagementInfo> selectContractManagementInfoList(ContractManagementInfo contractManagementInfo)
    {
        if(StringUtils.isEmpty(contractManagementInfo.getEnterpriseId())){
            if(SecurityUtils.getUserId()!=1&&SecurityUtils.getUserId()!=2){
                contractManagementInfo.setBelongTo(SecurityUtils.getOrgId());
            }
//            if (Objects.isNull(contractManagementInfo.getTelephone())){
//                contractManagementInfo.setCreationName(SecurityUtils.getUsername());
//            }
        }
        List<ContractManagementInfo> list = contractManagementInfoMapper.selectContractManagementInfoList(contractManagementInfo);
        //return mergeContractManagement(list);
        return list;
    }




    @Override
    public List<ContractManagementInfo> selectContractManagementReviewInfoList(ContractManagementInfo contractManagementInfo) {
        //2025-03-12 合同评审模块需要增加新增功能，这就导致该界面需要查询出用户审核的和自己新增的合同
        if(SecurityUtils.getUserId()!=1&&SecurityUtils.getUserId()!=2){
            if (SecurityUtils.getLoginUser().getUser().getIsAdmin().equals("1")){
                //说明是管理员
                contractManagementInfo.setBelongTo(SecurityUtils.getOrgId());
            }else {
                //说明是普通用户
                contractManagementInfo.setBelongTo(SecurityUtils.getOrgId());
                contractManagementInfo.setReviewer(SecurityUtils.getUsername());
            }
        }
        List<ContractManagementInfo> list = contractManagementInfoMapper.selectContractManagementReviewInfoList(contractManagementInfo);
        return mergeContractManagement(list);
    }

    /**
     * 新增【请填写功能名称】
     * 
     * @param contractManagementInfo 【请填写功能名称】
     * @return 结果
     */
    @Override
    public int insertContractManagementInfo(ContractManagementInfo contractManagementInfo)
    {
        return contractManagementInfoMapper.insertContractManagementInfo(contractManagementInfo);
    }

    /**
     * 修改【请填写功能名称】
     * 
     * @param contractManagementInfo 【请填写功能名称】
     * @return 结果
     */
    @Override
    public int updateContractManagementInfo(ContractManagementInfo contractManagementInfo)
    {
        return contractManagementInfoMapper.updateContractManagementInfo(contractManagementInfo);
    }

    /**
     * 批量删除【请填写功能名称】
     * 
     * @param contractIds 需要删除的【请填写功能名称】主键
     * @return 结果
     */
    @Override
    public int deleteContractManagementInfoByContractIds(String[] contractIds)
    {
        return contractManagementInfoMapper.deleteContractManagementInfoByContractIds(contractIds);
    }

    /**
     * 删除【请填写功能名称】信息
     * 
     * @param contractId 【请填写功能名称】主键
     * @return 结果
     */
    @Override
    public int deleteContractManagementInfoByContractId(String contractId)
    {
        return contractManagementInfoMapper.deleteContractManagementInfoByContractId(contractId);
    }

    @Override
    public int saveContractPayment(ContractPaymentMethodVo contractPaymentMethodVo) {
        int count = 0;
        List<ContractManagementInfo> contractManagementInfos = contractManagementInfoMapper.selectContractManagementByName(contractPaymentMethodVo.getContractName(),SecurityUtils.getOrgId());
        List<ContractManagementInfo> contractManagementInfoList = contractManagementInfoMapper.selectContractManagementByNumber(contractPaymentMethodVo.getContractNumber(),SecurityUtils.getOrgId());
        if(contractManagementInfos.size()>0){
            throw new RuntimeException("该合同名称已存在！");
        }else if (contractManagementInfoList.size()>0){
            throw new RuntimeException("该合同编号已存在！");
        }else{
            ContractManagementInfo managementInfo = new ContractManagementInfo();
            managementInfo.setContractId(contractPaymentMethodVo.getContractId());
            managementInfo.setContractName(contractPaymentMethodVo.getContractName());
            managementInfo.setContractNumber(contractPaymentMethodVo.getContractNumber());
            managementInfo.setRelatedContractId(contractPaymentMethodVo.getRelatedContractId());
            managementInfo.setRelatedContractName(contractPaymentMethodVo.getRelatedContractName());
            managementInfo.setClassificationId(contractPaymentMethodVo.getClassificationId());
            managementInfo.setContractAmount(contractPaymentMethodVo.getContractAmount());
            managementInfo.setSigningTime(contractPaymentMethodVo.getSigningTime());
            managementInfo.setEndTime(contractPaymentMethodVo.getEndTime());
            managementInfo.setEnterpriseId(contractPaymentMethodVo.getEnterpriseId());
            managementInfo.setEnterpriseName(contractPaymentMethodVo.getEnterpriseName());
            managementInfo.setCustomerAddress(contractPaymentMethodVo.getCustomerAddress());
            managementInfo.setCustomerContact(contractPaymentMethodVo.getCustomerContact());
            managementInfo.setTelephone(contractPaymentMethodVo.getTelephone());
            managementInfo.setSalespersonId(contractPaymentMethodVo.getSalespersonId());
            managementInfo.setSalespersonName(contractPaymentMethodVo.getSalespersonName());
            managementInfo.setAdditionalTerms(contractPaymentMethodVo.getAdditionalTerms());
            managementInfo.setState("0");
            managementInfo.setSign("0");
            managementInfo.setProvideSources(contractPaymentMethodVo.getProvideSources());
            managementInfo.setProvider(contractPaymentMethodVo.getProvider());
            managementInfo.setCost(contractPaymentMethodVo.getCost());
            managementInfo.setCreationId(SecurityUtils.getUserId());
            managementInfo.setCreationName(contractPaymentMethodVo.getCreationName());
            managementInfo.setCreationTime(new Timestamp(new Date().getTime()));
            managementInfo.setOperateTime(new Timestamp(new Date().getTime()));
            managementInfo.setOperateName(SecurityUtils.getUsername());
            managementInfo.setOperateId(SecurityUtils.getUserId());
            managementInfo.setOrganizationId(SecurityUtils.getOrgId());
            managementInfo.setOrganizationName(SecurityUtils.getOrgName());
            managementInfo.setDepartmentId(SecurityUtils.getDeptId());
            managementInfo.setDelFlag("0");
            managementInfo.setDepartmentName(SecurityUtils.getLoginUser().getUser().getDept().getDeptName());
            managementInfo.setBelongTo(SecurityUtils.getOrgId());
            managementInfo.setBusinessId(contractPaymentMethodVo.getBusinessId());
            count = contractManagementInfoMapper.insertContractManagementInfo(managementInfo);
            List<ContractPaymentMethod> methods = contractPaymentMethodVo.getContractPaymentMethods();
            for(int i = 0;i<methods.size();i++){
                ContractPaymentMethod contractPaymentMethod = new ContractPaymentMethod();
                contractPaymentMethod.setPaymentId(methods.get(i).getPaymentId());
                contractPaymentMethod.setContractId(methods.get(i).getContractId());
                contractPaymentMethod.setAmountCollected(methods.get(i).getAmountCollected());
                contractPaymentMethod.setPaymentName(methods.get(i).getPaymentName());
                contractPaymentMethod.setEstimatedCollectionTime(methods.get(i).getEstimatedCollectionTime());
                contractPaymentMethod.setRemark(methods.get(i).getRemark());
                contractPaymentMethodMapper.insertContractPaymentMethod(contractPaymentMethod);
            }
        }
        return count;
    }

    @Override
    public int updateContractPayment(ContractPaymentMethodVo contractPaymentMethodVo) {
        int count = 0;
        List<ContractManagementInfo> contractManagementInfos = contractManagementInfoMapper.selectContractManagementByName(contractPaymentMethodVo.getContractName(),SecurityUtils.getOrgId());
        List<ContractManagementInfo> contractManagementInfoList = contractManagementInfoMapper.selectContractManagementByNumber(contractPaymentMethodVo.getContractNumber(),SecurityUtils.getOrgId());
        if (contractManagementInfos.size() > 0 && !contractManagementInfos.get(0).getContractId().equals(contractPaymentMethodVo.getContractId())) {
            throw new RuntimeException("该合同名称已存在！");
        }else if(contractManagementInfoList.size() > 0 && !contractManagementInfoList.get(0).getContractId().equals(contractPaymentMethodVo.getContractId())){
            throw new RuntimeException("该合同编号已存在！");
        } else {
            ContractManagementInfo managementInfo = contractManagementInfoMapper.selectContractManagementInfoByContractId(contractPaymentMethodVo.getContractId());
            if(managementInfo==null){
               count = saveContractPayment(contractPaymentMethodVo);
            }else{
                managementInfo.setContractName(contractPaymentMethodVo.getContractName());
                managementInfo.setContractNumber(contractPaymentMethodVo.getContractNumber());
                managementInfo.setProvideSources(contractPaymentMethodVo.getProvideSources());
                managementInfo.setProvider(contractPaymentMethodVo.getProvider());
                managementInfo.setCost(contractPaymentMethodVo.getCost());
                managementInfo.setClassificationId(contractPaymentMethodVo.getClassificationId());
                managementInfo.setContractAmount(contractPaymentMethodVo.getContractAmount());
                managementInfo.setSigningTime(contractPaymentMethodVo.getSigningTime());
                managementInfo.setEndTime(contractPaymentMethodVo.getEndTime());
                managementInfo.setEnterpriseId(contractPaymentMethodVo.getEnterpriseId());
                managementInfo.setEnterpriseName(contractPaymentMethodVo.getEnterpriseName());
                managementInfo.setCustomerAddress(contractPaymentMethodVo.getCustomerAddress());
                managementInfo.setCustomerContact(contractPaymentMethodVo.getCustomerContact());
                managementInfo.setTelephone(contractPaymentMethodVo.getTelephone());
                managementInfo.setSalespersonId(contractPaymentMethodVo.getSalespersonId());
                managementInfo.setSalespersonName(contractPaymentMethodVo.getSalespersonName());
                managementInfo.setAdditionalTerms(contractPaymentMethodVo.getAdditionalTerms());
                managementInfo.setOperateName(SecurityUtils.getUsername());
                managementInfo.setOperateId(SecurityUtils.getUserId());
                managementInfo.setOperateTime(new Timestamp(new Date().getTime()));
                managementInfo.setDelFlag("0");
                managementInfo.setBusinessId(contractPaymentMethodVo.getBusinessId());
                count = contractManagementInfoMapper.updateContractManagementInfo(managementInfo);
                contractPaymentMethodMapper.deleteContractPaymentMethodByContractId(contractPaymentMethodVo.getContractId());
                List<ContractPaymentMethod> paymentMethods = contractPaymentMethodVo.getContractPaymentMethods();
                for (int i = 0; i < paymentMethods.size(); i++) {
                    ContractPaymentMethod method = new ContractPaymentMethod();
                    method.setPaymentId(paymentMethods.get(i).getPaymentId());
                    method.setContractId(contractPaymentMethodVo.getContractId());
                    method.setAmountCollected(paymentMethods.get(i).getAmountCollected());
                    method.setPaymentName(paymentMethods.get(i).getPaymentName());
                    method.setEstimatedCollectionTime(paymentMethods.get(i).getEstimatedCollectionTime());
                    contractPaymentMethodMapper.insertContractPaymentMethod(method);
                }
            }
            return count;
        }
    }

    @Override
    public int updateContractState(ContractPaymentMethodVo contractPaymentMethodVo) {
        ContractManagementInfo contractManagementInfo = contractManagementInfoMapper.selectContractManagementInfoByContractId(contractPaymentMethodVo.getContractId());
        contractManagementInfo.setState("1");
        return contractManagementInfoMapper.updateContractManagementInfo(contractManagementInfo);
    }

    @Override
    public int editMainClass(BusinessMainClassVo businessMainClassVo) {
        boolean flag = businessMainClassVo.getContractId().contains(",");
        int count = 0;
        if (flag) {
            String[] contractIds = businessMainClassVo.getContractId().split(",");
            for (int i = 0; i < contractIds.length; i++) {
                ContractManagementInfo information = contractManagementInfoMapper.selectContractManagementInfoByContractId(contractIds[i]);
                information.setClassificationId(businessMainClassVo.getMainClassId());
                information.setOperateTime(new Timestamp(new Date().getTime()));
                information.setOperateName(SecurityUtils.getUsername());
                information.setOperateId(SecurityUtils.getUserId());
                count = contractManagementInfoMapper.updateContractManagementInfo(information);
            }
        } else {
            ContractManagementInfo information = contractManagementInfoMapper.selectContractManagementInfoByContractId(businessMainClassVo.getContractId());
            information.setClassificationId(businessMainClassVo.getMainClassId());
            information.setOperateTime(new Timestamp(new Date().getTime()));
            information.setOperateName(SecurityUtils.getUsername());
            information.setOperateId(SecurityUtils.getUserId());
            count =contractManagementInfoMapper.updateContractManagementInfo(information);
        }
        return count;
    }



    private List<ContractManagementInfo> mergeContractManagement(List<ContractManagementInfo> list) {
        Map<String, ContractManagementInfo> map = new HashMap<>();
        for (int i = 0; i < list.size(); i++) {
            String key = list.get(i).getContractId();
            if (map.containsKey(key)) {
                if(!map.get(key).getProductName().contains(list.get(i).getProductName())){
                    list.get(i).setProductName(list.get(i).getProductName() + ","+map.get(key).getProductName());
                }
                map.put(key, list.get(i));
            } else {
                map.put(key, list.get(i));
            }
        }
        List<ContractManagementInfo> managementInfoList = new ArrayList<>();
        for (String key : map.keySet()) {
            managementInfoList.add(map.get(key));
        }
        Collections.sort(managementInfoList, new Comparator<ContractManagementInfo>() {
            @Override
            public int compare(ContractManagementInfo p1, ContractManagementInfo p2) {
                return p2.getCreationTime().compareTo(p1.getCreationTime()); // 根据时间进行排序
            }
        });
        return managementInfoList;
    }
}
